// pages/auth/auth.js
var encryp = require('../../assets/js/encryp.js')
var wxRequest = require('../../assets/js/wxRequest.js')
var common = require('../../assets/js/common.js')
var lockjs = require('../../assets/js/database/lock.js')
var base = require('../../assets/js/base.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    hiddenmodalput: true,
    currentPage: 1,      //当前页
    keyOrLock: true,
    token: '',
    randomKey: '',
    sign: '',
    userId: '',
    array1: [[], []],
    index1:'',
    array2: ['库房'],
    index2: 0,
    houseArray: [],  //库房
    house: [],       //当前选择的库房
    authNoteName:'',
    receiveType:['钥匙','锁具'],
    index3: 0,
    allUserArray: [], //审批人
    userArray: [],   //审批人(只包含名字)
    index4: '',
    
    deptArray: [],   //区域数据(包含区)

    checkboxItems: [],
    keyOrLockArray:''
  },
  /**
   * 根据用户获取区域
   */
  getDept: function (e) {
    var that = this;
    var simpleObject = {
      id: that.data.userId
    };
    var param = common.packParam(that.data.randomKey, simpleObject);
    var url = getApp().globalData.httpUrl + '/dept/byUserlist';
    var info = wxRequest.postRequest(url, param, that.data.token).
      then(res => {
        var data = {
          array1: that.data.array1
        };
        //把区域列表设置到piker组件
        data.array1[0].push(res.data.title)
        var children = res.data.children;
        //该用户属于市下
        var flag = common.isArray(children)
        if (flag) {
          //仅设置区的数据(默认用户只属于一个市)
          that.setData({
            deptArray: children
          })
          for (var i = 0; i < children.length; i++) {
            data.array1[1].push(children[i].title);
          }
        } else {
          that.setData({
            deptArray: res.data
          })
        }
        this.setData(data)
      })
  },
  /**
   * 获取库房
   */
  getHouse: function (deptId) {
    var that = this;
    var simpleObject = {
      id: deptId
    };
    var param = common.packParam(that.data.randomKey, simpleObject);
    var url = getApp().globalData.httpUrl + '/house/getHouseByDept';
    var info = wxRequest.postRequest(url, param, that.data.token).
      then(res => {
        that.data.array2 = [];
        var data = {
          array2: that.data.array2
        };
        for (var i = 0; i < (res.data).length; i++) {
          data.array2.push(res.data[i].houseName)
        }
        this.setData(data)
        that.setData({
          houseArray: res.data
        })
      })
  },
  /**
   * 根据库房获取钥匙列表
   */
  getKeyByHouse: function (houseId, offset) {
    var that = this;
    var simpleObject = {
      id: houseId,
      offset: offset,
      limit: getApp().globalData.limit
    };
    //封装参数
    var param = common.packParam(that.data.randomKey, simpleObject);
    //获取锁信息
    var url = getApp().globalData.httpUrl + '/key/getKeyByHouse';
    var info = wxRequest.postRequest(url, param, that.data.token).
      then(res => {
        var datas = res.data
        var data = {
          checkboxItems: that.data.checkboxItems,
          showLoadMore: that.data.showLoadMore
        };
        
        if (datas == '' || datas == []) {
        } else {
          for (var i = 0; i < datas.length;i++){
            data.checkboxItems.push(datas[i])
          }
        }
        this.setData(data)
      })
  },
  /**
   * 根据库房获取锁列表
   */
  getLockByHouse: function (houseId, offset) {
    var that = this;
    var simpleObject = {
      id: houseId,
      offset: offset,
      limit: getApp().globalData.limit
    };
    //封装参数
    var param = common.packParam(that.data.randomKey, simpleObject);
    //获取锁信息
    var url = getApp().globalData.httpUrl + '/lock/getLockByHouse';
    var info = wxRequest.postRequest(url, param, that.data.token).
      then(res => {
        var datas = res.data
        var data = {
          checkboxItems: that.data.checkboxItems,
          showLoadMore: that.data.showLoadMore
        };

        if (res.data == '' || res.data == []) {
          
        } else {
          for (var i = 0; i < datas.length; i++) {
            data.checkboxItems.push(datas[i])
          }
        }
        this.setData(data)
      })
  },
  /**
   * 获取名称输入框的内容
   */
  nameInput: function(e){
    var that = this;
    that.setData({
      authNoteName: e.detail.value
    })
  },
    
  /**
   * 根据当前用户获取审批人员
   */
  getCheckUser:function (userId){
    var that = this;
    var simpleObject = {
      id: userId
    };
    var param = common.packParam(that.data.randomKey, simpleObject);
    var url = getApp().globalData.httpUrl + '/user/getCheckUser';
    var info = wxRequest.postRequest(url, param, that.data.token).
      then(res => {
        console.log(res.data)
        var array = res.data;
        that.setData({
          allUserArray: array
        })
        for (var i = 0; i < array.length; i++) {
          array[i] = array[i].name
        }
        that.setData({
          userArray: array
        })
      })
  },
  /**
   * 表单提交
   */
  inputSubmit: function(){
    var that = this;
    var types;
    if (that.data.keyOrLock){
      types = 1
    }else{
      types = 2
    }
    var simpleObject = {
      types: types,
      name: base.utf16to8(that.data.authNoteName),
      userId: that.data.userId,
      keyOrLockArray: that.data.keyOrLockArray,
      checkUserId: that.data.allUserArray[that.data.index4].id
    };
    var param = common.packParam(that.data.randomKey, simpleObject);
    //提交申请
    var url = getApp().globalData.httpUrl + '/reviceNote/applyNote';
    var info = wxRequest.postRequest(url, param, that.data.token).
      then(res => {
        console.log(res.data)
        if (parseInt(res.data)>=1){
          wx.navigateTo({
            url: '/pages/msg_success/msg_success'
          })
        }
      })
  },
  
 

  // ------------picker改变事件begin---------------
  /**
   * 区域列表滚动事件
   */
  bindPickerChange1: function (e) {
    var that = this;
    console.log('sss'+e.detail.value)
    that.setData({
      index1: e.detail.value
    })
    //选择区域后获取库房数据
    var jsons = that.data.deptArray;
    if (jsons.length) {
      var dept = that.data.deptArray[that.data.index1[1]];
    } else {          //只有一个区，不需要滚动选择
      var dept = that.data.deptArray;
    }
    that.getHouse(dept.id)
    //获取审批人员
    that.getCheckUser(that.data.userId);
  },
  /**
   * 库房列表滚动事件
   */
  bindPickerChange2: function (e) {
    var that = this;
    console.log(e.detail.value)
    that.setData({
      index2: e.detail.value
    })
    //获取锁列表
    var house = that.data.houseArray[e.detail.value]
    //把页码设置为第一页 并设置当前库房
    that.setData({
      house: house,
      currentPage: 1
    })
  },
  /**
   * 领用类型滚动
   */
  bindTypeChange: function(e){
    var that = this;
    // 领用类型改变，清空旧数据
    that.setData({
      checkboxItems: []
    })
    console.log('TypeChange' + e.detail.value)
    var index = parseInt(e.detail.value)
    var flag = false;
    if (index==0){     //钥匙
      flag = true;
      that.getKeyByHouse(that.data.house.id, that.data.currentPage)

    }else{             //锁具
      flag = false;
      that.getLockByHouse(that.data.house.id, that.data.currentPage)
    }
    that.setData({
      index3: index,
      keyOrLock: flag
    })
  },
  bindUserChange: function(e){
    var that = this;
    console.log('userPicker' + e.detail.value)
    that.setData({
      index4: e.detail.value
    })
  },
  checkboxChange: function (e) {
    console.log('checkbox发生change事件，携带value值为：', e.detail.value);

    var checkboxItems = this.data.checkboxItems, values = e.detail.value;
    console.log(checkboxItems)
    console.log(values)
    for (var i = 0, lenI = checkboxItems.length; i < lenI; ++i) {
      checkboxItems[i].checked = false;

      for (var j = 0, lenJ = values.length; j < lenJ; ++j) {
        if (checkboxItems[i].id == values[j]) {
          checkboxItems[i].checked = true;
          break;
        }
      }
    }
    var value = values.join(",");

    this.setData({
      checkboxItems: checkboxItems,
      keyOrLockArray: value
    });
  },
  /**
   * 加载更多
   */
  loadMore: function(){
    var that = this;
    var page = that.data.currentPage + 1;
    that.setData({
      currentPage: page
    })
    if (that.data.keyOrLock) {     //钥匙
      that.getKeyByHouse(that.data.house.id, that.data.currentPage)

    } else {             //锁具
      that.getLockByHouse(that.data.house.id, that.data.currentPage)
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    // 每个页面都需要先获取缓存中的token和security
    var tokens = wx.getStorageSync('token')
    var randomKey = wx.getStorageSync('randomKey')
    var sign = wx.getStorageSync('sign')
    var id = wx.getStorageSync('id')
    if (tokens && randomKey) {
      that.setData({
        token: tokens,
        randomKey: randomKey,
        sign: sign,
        userId: id
      })
    }
    that.getDept();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  openAlert: function () {
    this.setData({
      hiddenmodalput: !this.data.hiddenmodalput
    })
  },
  modalinput: function () {
  },
  //取消按钮
  cancel: function () {    
    this.setData({      hiddenmodalput: true    });  
    console.log('用户点击取消')
    },  
  //确认    
  confirm: function () {
    this.setData({      hiddenmodalput: true    })  
    console.log('用户点击确认')
  }


})